import redis
from connect_to_redis import BaseRedisConnection


class TestHash(BaseRedisConnection):
    # hset/hget: 设置/获取散列值
    # hmset/hmget:设置/获取多对散列值
    # hsetnx:如果散列已经存在，则不设置
    # hkeys/hvals:返回所有keys/values
    # hlen:返回散列包含域（field）的数量
    # hdel:删除散列指定的域（field）
    # hexists:判断是否存在

    def test_hset(self):
        # hset/hget: 设置/获取散列值
        result = self.conn.hset('stu:0001','name','李丽')
        print(result)
        # 插入之前判断是否已经存在
        exists = self.conn.hexists('stu:0001','name')
        print('exists:',exists)
        # 如果已经存在，则不插入
        result = self.conn.hsetnx('stu:0001','name','王丽')
        print('res:',result)


    def test_hmset(self):
        # hset/hget: 设置/获取散列值
        m = {
            'name':'Bob',
            'age':21,
            'grade':98
        }
        result = self.conn.hset('stu:0003', mapping=m)
        print(result)
        keys = self.conn.hkeys('stu:0003')
        print('keys:',keys)

    def test_hdel(self):
        # hdel:删除散列指定的域（field）
        length = self.conn.hlen('stu:0003')
        print('length:',length)
        result = self.conn.hdel('stu:0003','age')
        print('res:',result)
        length = self.conn.hlen('stu:0003')
        print('length2:', length)


    def register(self,username,password,nickname):
        # 模拟用户注册
        user_info = {
            'username': username,
            'password': password,
            'nickname': nickname
        }
        key = f'user:{username}'
        result = self.conn.hset(key,mapping=user_info)
        print(result)

    def get_user_info(self,username):
        # 获取用户信息
        key = f'user:{username}'
        user = self.conn.hmget(key,'username','password','nickname')
        print(user)
        print('username:',user[0])



def main():
    str_obj = TestHash()
    # str_obj.test_hset()
    # str_obj.test_hmset()
    # str_obj.test_hdel()
    # str_obj.register('wangwu','123456','王五')
    str_obj.get_user_info('wangwu')



if __name__ == '__main__':
    main()